package com.geekaca.d09.work;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

public class Test3_extend {

    public static void main(String[] args) {
        // 创建要复制的.java文件的集合
        ArrayList<File> fileList = new ArrayList<>();
        // 目标文件目录
        File path = new File("StudyIO1\\src");
        // 存放文件的文本文件
        File distFile = new File("StudyIO1\\AllProjectJavaFiles.txt");
        // 找到的文件集合
        fileList = searchFile(path, fileList);
        //
        fileList.forEach(file -> {
            System.out.println("准备写入文件: " + file + " 到目标文件");
            try {
                writeFile(file, distFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        });

    }

    public static ArrayList<File> searchFile(File dir, ArrayList<File> fileList) {
        if (dir != null && dir.isDirectory()) {
            File[] files = dir.listFiles();

            if (files.length != 0) {
                for (int i = 0; i < files.length; i++) {
                    File curFile = files[i];
                    if (curFile.isFile()) {
                        if (curFile.getName().contains(".java")) {
                            fileList.add(curFile);
                        }
                    } else {
                        searchFile(curFile, fileList);
                    }
                }
            }
        }
        return fileList;
    }

    public static void writeFile(File orgFile, File distFile) throws FileNotFoundException {
        System.out.println("writing file : " + orgFile.getName());
        InputStream is = new FileInputStream(orgFile);
        OutputStream os = new FileOutputStream(distFile, true); // 追加写入方式
        try (is; os) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.write("\r\n".getBytes(StandardCharsets.UTF_8));

            System.out.println("文件: " + orgFile.getName() + "写入完成");
            System.out.println("====================================");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}
